<?php class DBConnection{
	
	private $database;
	
	function __construct(){
		
		if(!file_exists('ProducerDB.sqlite')){
			$this->createDatabase();
			$this->createProducerTable();
			$this->populateProducerTable();
		}
		else{
			$this->createDatabase();
		}
	}
	
	/**
	 * Function to Create the ProducerDB database as SQLite
	 * @access private
	 * @param -
	 * @return -
	 */
	private function createDatabase(){
		try {
			$this->database = new PDO('sqlite:ProducerDB.sqlite');
			$this->database->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		}
	
		catch(PDOException $e) {
			die("FEL! : " .$e->getMessage());
		}
	}
	
	/**
	 * Function to Create the Producertable
	 * @access private
	 * @param -
	 * @return -
	 */
	private function createProducerTable(){
		$query='CREATE TABLE Producer (ProducerId INTEGER PRIMARY KEY, latitude REAL, longitude REAL, description TEXT)';

		try {
			$statement = $this->database->prepare($query);
			if(!$statement->execute()) {
				die("Gick inte att skapa tabellen");
			}
		}
		catch(PDOException $e) {
			die("FEL! : " .$e->getMessage());
		}
	}
	
	/**
	 * Function to populate the Producertable
	 * @access private
	 * @param -
	 * @return -
	 */
	private function populateProducerTable(){
		//Call the private method to get filecontent
		$dataArray = $this->getFileContent();	
			
		
		foreach ($dataArray as $value) {
	
			$query = "INSERT INTO 'Producer' (ProducerId, latitude, longitude, description) VALUES('$value[2]', '$value[0]', '$value[1]', '$value[3]');";

			try {
				$statement = $this->database->prepare($query);
				if(!$statement->execute()) {
					die("Gick inte att skapa tabellen");
				}
			}
			catch(PDOException $e) {
				die("FEL! : " .$e->getMessage());
			}
	
		}
	}
	
	/**
	 * Function to get contents out of comma seperated file
	 * @access private
	 * @param - 
	 * @return Array
	 */	
	private function getFileContent($a_ = null){
		$lines = file('data.txt');
	
		$array = array();
	
		foreach ($lines as $line) {
	    	$array[] = explode(',', $line);
		}
		
		$returnArray = array();
		
		foreach($array as $producerArray){

			$producerArray[0] = (float)trim($producerArray[0]);
			$producerArray[1] = (float)trim($producerArray[1]);
			$producerArray[2] = (int)trim($producerArray[2]);
			$producerArray[3] = trim($producerArray[3]);
			
			$returnArray[] = $producerArray;	
		}
		
		
		return $returnArray;
	}
	
	function prepare($sql){
		return $this->database->prepare($sql);
	}
	
	function lastInsertId(){
		return $this->database->lastInsertId();
	}
}
?>